//
//  ViewController.m
//  Exam12-1
//
//  Created by 孙晓晔 on 2017/4/19.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "ViewController.h"
#import <MapKit/MapKit.h>

#import "Car.h"
#import "CarDayAnnotation.h"
#import "CarDayAnnotationView.h"
#import "CarHourAnnotation.h"
#import "CarHourAnnotationView.h"

#import "CarView.h"
#import "MySlider.h"

@interface ViewController ()<MKMapViewDelegate,CLLocationManagerDelegate,UISearchBarDelegate>
@property(nonatomic,strong) MKMapView *mapView; // 地图视图
@property(nonatomic,strong) CLLocationManager *locationManager; // 定位管理
@property(nonatomic,strong) CLLocation *location; // 定位

@property(nonatomic,strong) MKLocalSearch *localSearch; // 本地搜索

@property(nonatomic,strong) UISearchBar *searchBar; // 搜索
@property(nonatomic,strong) UITextField *textField;
@property(nonatomic,strong) NSString *titleString;

@property(nonatomic,copy)NSArray *carDayArr; //日租 存放plist读取的数据
@property(nonatomic,copy)NSArray *carHourArr; // 时租 存放plist读取的数据

//@property(nonatomic,strong) UIView *typeView; // 租车类型选择视图
@property(nonatomic,strong) CarView *carView; // 租车信息视图
@property(nonatomic,strong) MySlider *slider;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
//    [self aaa];
    
    [self setUp];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setUp {
    
    if ([CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位功能开启");
        
        CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
        if (status == kCLAuthorizationStatusNotDetermined) {
            [self.locationManager requestAlwaysAuthorization];
        }
    }
    
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    // 经纬度 = 22.568630, 113.913530
    
    MKCoordinateRegion region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(22.568630, 113.913530), MKCoordinateSpanMake(0.1, 0.1));
    
    self.mapView.region = [self.mapView regionThatFits:region];
    
    CLLocationCoordinate2D coordinate2D;
    coordinate2D.latitude = 39.936846;
    coordinate2D.longitude = 116.503729;
    
    MKPointAnnotation *pointAnnotation = [[MKPointAnnotation alloc]init];
    pointAnnotation.title = @"当前位置";
    pointAnnotation.subtitle = @"位置说明";
    pointAnnotation.coordinate = coordinate2D;
    
    [self.mapView addAnnotation:pointAnnotation];
    
    [self searchBar];
    
    [self btn];
    
//    [self type];
    
    UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
    
    [_mapView addGestureRecognizer:longPressGestureRecognizer];
    
    __weak ViewController *weakSelf = self;
    
    self.slider.block=^(int index){
        // NSLog(@"当前index==%d",index);
        
        switch (index) {
            case 0:
                [weakSelf btn1:nil];
                break;
            case 1:
                [weakSelf btn2:nil];
                break;
                
            default:
                [weakSelf btn_default];
                break;
        }
        
    };
}

-(MySlider *)slider {
    if (_slider == nil) {
        
        UIView *view = [[UIView alloc]init];
        view.translatesAutoresizingMaskIntoConstraints = NO;
        view.backgroundColor = [UIColor whiteColor];
        
        [self.view addSubview:view];
        
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[view]-0-|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(view)]];
        
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view(90)]-0-|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(view)]];
        
        _slider = [[MySlider alloc] initWithFrame:CGRectMake(10, 0, 350, 80) titles:@[@"日租",@"时租",@"长租",@"试驾"] defaultIndex:0 sliderImage:[UIImage imageNamed:@"car"]];
        
        [view addSubview:_slider];
    }
    
    return _slider;
}

-(void)longPressed:(UILongPressGestureRecognizer*)recognizer {
    NSLog(@"手势长按", nil);
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [recognizer locationInView:_mapView];
        CLLocationCoordinate2D coordinate2D = [_mapView convertPoint:point toCoordinateFromView:_mapView];

        [_mapView removeAnnotations:_mapView.annotations];
        
        CLLocation *location = [[CLLocation alloc]initWithLatitude:coordinate2D.latitude longitude:coordinate2D.longitude];
        
        [self reverseGeocoder:location];
    }
}

// 类型选择
-(void)type {
    
    UIView *view = [[UIView alloc]init];
    view.translatesAutoresizingMaskIntoConstraints = NO;
    view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:view];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[view]-0-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(view)]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view(90)]-0-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(view)]];
    
//    self.typeView = view;

    UIButton *btn1 = [[UIButton alloc]init];
    btn1.translatesAutoresizingMaskIntoConstraints = NO;
    btn1.backgroundColor = [UIColor grayColor];
    btn1.layer.cornerRadius = 5;
    btn1.clipsToBounds = YES;
    
    [btn1 setTitle:@"日租" forState:UIControlStateNormal];
    
    [btn1 addTarget:self action:@selector(btn1:) forControlEvents:UIControlEventTouchUpInside];
    
    [view addSubview:btn1];
    
    UIButton *btn2 = [[UIButton alloc]init];
    btn2.translatesAutoresizingMaskIntoConstraints = NO;
    btn2.backgroundColor = [UIColor grayColor];
    btn2.layer.cornerRadius = 5;
    btn2.clipsToBounds = YES;
    [btn2 setTitle:@"时租" forState:UIControlStateNormal];
    
    [btn2 addTarget:self action:@selector(btn2:) forControlEvents:UIControlEventTouchUpInside];
    
    [view addSubview:btn2];
    
    UIButton *btn3 = [[UIButton alloc]init];
    btn3.translatesAutoresizingMaskIntoConstraints = NO;
    btn3.backgroundColor = [UIColor grayColor];
    btn3.layer.cornerRadius = 5;
    btn3.clipsToBounds = YES;
    [btn3 setTitle:@"长租" forState:UIControlStateNormal];
    
    [view addSubview:btn3];
    
    UIButton *btn4 = [[UIButton alloc]init];
    btn4.translatesAutoresizingMaskIntoConstraints = NO;
    btn4.backgroundColor = [UIColor grayColor];
    btn4.layer.cornerRadius = 5;
    btn4.clipsToBounds = YES;
    [btn4 setTitle:@"试驾" forState:UIControlStateNormal];
    
    [view addSubview:btn4];
    
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[btn1]-20-[btn2(==btn1)]-20-[btn3(==btn1)]-20-[btn4(==btn1)]-20-|"
                                                                      options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(btn1,btn2,btn3,btn4)]];
    
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[btn1(44)]-23-|"
                                                                      options:kNilOptions
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(btn1,btn2,btn3,btn4)]];
}

-(void)btn1:(id)sender {
    NSLog(@"日租", nil);
    
    [_mapView removeAnnotations:_mapView.annotations];
    
    for (Car *car in self.carDayArr) {
        
        CarDayAnnotation *dayAnnotation = [[CarDayAnnotation alloc] init];
        [dayAnnotation setCar:car];
        
        [_mapView addAnnotation:dayAnnotation];
    }
}

-(void)btn2:(id)sender {
    NSLog(@"时租", nil);
    
    [_mapView removeAnnotations:_mapView.annotations];
    
    for (Car *car in self.carHourArr) {
        
        CarHourAnnotation *hourAnnotation = [[CarHourAnnotation alloc] init];
        [hourAnnotation setCar:car];
        
        [_mapView addAnnotation:hourAnnotation];
    }
}

-(void)btn_default {
    [_mapView removeAnnotations:_mapView.annotations];
    
    MKCoordinateRegion region = self.mapView.region;
    region.center = self.location.coordinate;
//    region.span = MKCoordinateSpanMake(0.01, 0.01);
    
    [self.mapView regionThatFits:region];
    
    self.mapView.region = [self.mapView regionThatFits:region];
}

-(UISearchBar *)searchBar {
    if (_searchBar == nil) {
        _searchBar = [[UISearchBar alloc]init];
        
        _searchBar.delegate = self;
        
        _searchBar.translatesAutoresizingMaskIntoConstraints = NO;
        
        _searchBar.backgroundColor = [UIColor whiteColor];
        _searchBar.placeholder = @"搜地点";
        
        [_searchBar setTranslucent:YES];
        [_searchBar setShowsSearchResultsButton:YES];
        
        [self.view addSubview:_searchBar];
        
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_searchBar]-|"
                                                                          options:kNilOptions
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(_searchBar)]];
        
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[_searchBar(44)]"
                                                                          options:kNilOptions
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(_searchBar)]];
    }
    
    return _searchBar;
}

// 执行搜索
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"搜索", nil);
    
    [self.searchBar resignFirstResponder];
    
    if (_searchBar.text.length == 0) {
        return;
    }
    
    // [self geocoder:_searchBar.text];
    
    [_mapView removeAnnotations:_mapView.annotations];
    
    MKLocalSearchRequest *searchRequest = [[MKLocalSearchRequest alloc]init];
    searchRequest.naturalLanguageQuery = _searchBar.text;
    
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(22.568630, 113.913530), 8000, 8000);
    
    searchRequest.region = region;
    
    _localSearch = [[MKLocalSearch alloc] initWithRequest:searchRequest];
    
    [_localSearch startWithCompletionHandler:^(MKLocalSearchResponse * _Nullable response, NSError * _Nullable error) {
       
        if (error || response.mapItems.count == 0) {
            NSLog(@"error:%@", error);
        } else {
            NSArray *itemArr = response.mapItems;
            
            for (MKMapItem *item in itemArr) {
                
                MKPlacemark *placemark = item.placemark;
                
                NSLog(@"%@", placemark.name);

                
                MKPointAnnotation *pointAnnotation = [[MKPointAnnotation alloc]init];
                pointAnnotation.title = placemark.name;
                pointAnnotation.coordinate = CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude);
                
                [_mapView addAnnotation:pointAnnotation];
            }
        }
    }];
    
}


-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"编辑完成", nil);
    [self.searchBar resignFirstResponder];
}

// 定位／放大／缩小按钮
-(void)btn {
    
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor whiteColor];
    
    view.layer.cornerRadius = 5;
    view.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.view addSubview:view];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[view(40)]-15-|"
                                                                      options:kNilOptions
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(view)]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view(80)]-100-|"
                                                                      options:kNilOptions
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(view)]];
    
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"line"]];
    
    imageView.frame = CGRectMake(5, 35, 30, 10);
    
    [view addSubview:imageView];
    
    UIButton *plusBtn = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 30, 30)];
    [plusBtn setImage:[UIImage imageNamed:@"plus"] forState:UIControlStateNormal];
    [plusBtn setImage:[UIImage imageNamed:@"plus"] forState:UIControlStateHighlighted];
    
    
    [plusBtn addTarget:self action:@selector(plus) forControlEvents:UIControlEventTouchUpInside];
    
    [view addSubview:plusBtn];
    
    UIButton *minusBtn = [[UIButton alloc]initWithFrame:CGRectMake(5, 45, 30, 30)];
    
    [minusBtn setImage:[UIImage imageNamed:@"minus"] forState:UIControlStateNormal];
    [minusBtn setImage:[UIImage imageNamed:@"minus"] forState:UIControlStateHighlighted];
    
    [minusBtn addTarget:self action:@selector(minus) forControlEvents:UIControlEventTouchUpInside];
    
    [view addSubview:minusBtn];
    
    UIButton *centerBtn = [[UIButton alloc]init];
    centerBtn.translatesAutoresizingMaskIntoConstraints = NO;
    centerBtn.backgroundColor = [UIColor whiteColor];
    
    centerBtn.layer.cornerRadius = 5;
    centerBtn.clipsToBounds = YES;
    
    [centerBtn setImage:[UIImage imageNamed:@"nav"] forState:UIControlStateNormal];
    [centerBtn addTarget:self action:@selector(center) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:centerBtn];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[centerBtn(40)]"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(centerBtn)]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[centerBtn(40)]-100-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(centerBtn)]];
    
    [self btn1:nil];
}

-(void)plus {
    NSLog(@"放大");
    
    MKCoordinateRegion region = self.mapView.region;
    if (region.span.latitudeDelta < 0.002) {
        return;
    }
    
    region.span.latitudeDelta *= 0.5;
    region.span.longitudeDelta *= 0.5;
    
    NSLog(@"latitude = %f", region.span.latitudeDelta);
    
    self.mapView.region = [self.mapView regionThatFits:region];
}

-(void)minus {
    NSLog(@"放小");
    
    MKCoordinateRegion region = self.mapView.region;
    
    if (region.span.latitudeDelta > 50) {
        return;
    }
    
    region.span.latitudeDelta *= 1.5;
    region.span.longitudeDelta *= 1.5;
    
    NSLog(@"latitude = %f", region.span.latitudeDelta);
    
    self.mapView.region = [self.mapView regionThatFits:region];
}

-(void)center {
    NSLog(@"居中");
    
    MKCoordinateRegion region = self.mapView.region;
    region.center = self.location.coordinate;
//    region.span = MKCoordinateSpanMake(0.01, 0.01);
    
    self.mapView.region = [self.mapView regionThatFits:region];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [_searchBar resignFirstResponder];
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    NSLog(@"屏幕旋转", nil);
    
    _mapView.frame = self.view.bounds;
}

// 懒加载
-(MKMapView *)mapView {
    
    if (_mapView == nil) {
        _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
        
        _mapView.delegate = self;
        _mapView.mapType = MKMapTypeStandard;
        
        _mapView.zoomEnabled = YES;
        _mapView.scrollEnabled = YES;
        _mapView.rotateEnabled = YES;
        
        [self.view addSubview:self.mapView];
    }
    
    return _mapView;
}

// 懒加载
-(CLLocationManager *)locationManager {
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc]init];
        
        if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_locationManager requestWhenInUseAuthorization];
        }
        
        _locationManager.delegate = self;
        
        // 设置定位精度
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 设置距离筛选
        _locationManager.distanceFilter = 100;
        
        // 开始定位
        [_locationManager startUpdatingLocation];
    }
    
    return _locationManager;
}

// 懒加载
-(NSArray *)carHourArr {
    if (_carDayArr == nil) {
        NSString *strPath = [[NSBundle mainBundle]pathForResource:@"car2" ofType:@"plist"];
        NSArray *arr = [NSArray arrayWithContentsOfFile:strPath];
        
        NSMutableArray *muArr = [NSMutableArray array];
        
        for (NSDictionary *dict in arr) {
            Car *obj = [Car carWithDict:dict];
            
            [muArr addObject:obj];
        }
        
        _carDayArr = muArr;
    }
    
    return _carDayArr;
}

// 懒加载
-(NSArray *)carDayArr {
    if (_carHourArr == nil) {
        NSString *strPath = [[NSBundle mainBundle]pathForResource:@"car1" ofType:@"plist"];
        NSArray *arr = [NSArray arrayWithContentsOfFile:strPath];
        
        NSMutableArray *muArr = [NSMutableArray array];
        
        for (NSDictionary *dict in arr) {
            Car *obj = [Car carWithDict:dict];
            
            [muArr addObject:obj];
        }
        
        _carHourArr = muArr;
    }
    
    return _carHourArr;
}

// 懒加载
-(UIView *)carView {
    if (_carView == nil) {
        CarView *view = [[CarView alloc]initWithFrame:self.view.bounds];
        
        view.translatesAutoresizingMaskIntoConstraints = NO;
        view.backgroundColor = [UIColor whiteColor];
        
        [self.view addSubview:view];
        
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[view]-|"
                                                                          options:kNilOptions
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(view)]];
        
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view(80)]-10-|"
                                                                          options:kNilOptions
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(view)]];
        view.alpha = .0f;
        
        _carView = view;
    }
    
    return _carView;
}

#pragma mark - CLLocationManagerDelegate

// 授权状态发生改变的时侯执行
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined: {
            NSLog(@"用户还未决定授权");
            break;
        }
        case kCLAuthorizationStatusRestricted: {
            NSLog(@"访问受限");
            break;
        }
        case kCLAuthorizationStatusDenied:
            // 类方法，判断是否开启定位服务
            if ([CLLocationManager locationServicesEnabled]) {
                NSLog(@"定位服务开启，被拒绝");
            } else {
                NSLog(@"定位服务关闭，不可用");
            }
            break;
        case kCLAuthorizationStatusAuthorizedAlways: {
            NSLog(@"获得前后台授权");
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse: {
            NSLog(@"获得前台授权");
            break;
        }
        default:
            break;
    }
}

// 定位成功以后执行
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    [_locationManager stopUpdatingLocation];
    
    CLLocation *location = [locations lastObject];
    
    [self reverseGeocoder:location];
    
    MKCoordinateRegion region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude), MKCoordinateSpanMake(0.1, 0.1));
    
    [_mapView setRegion:[_mapView regionThatFits:region] animated:YES];
}

// 定位出错时执行
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"error:%@", error);
    
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}

#pragma mark Geocoder

-(void)geocoder:(NSString*)str {
    
    if (self.location == nil) {
        return;
    }
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    
    CLRegion *region = [[CLCircularRegion alloc]initWithCenter:self.location.coordinate radius:10000.0 identifier:@"my"];
    
    [geocoder geocodeAddressString:str inRegion:region completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error || placemarks.count == 0) {
            NSLog(@"error");
        } else {
            NSLog(@"关键字 = %@, 结果%ld", str, placemarks.count);
            
            CLPlacemark *placemark = placemarks.firstObject;
            
            MKCoordinateRegion coordinateRegion = MKCoordinateRegionMake(CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude), MKCoordinateSpanMake(0.1, 0.1));
            
            [_mapView setRegion:coordinateRegion animated:YES];
            
            MKPointAnnotation *pointAnnotation = [[MKPointAnnotation alloc]init];
            pointAnnotation.title = placemark.name;
            pointAnnotation.coordinate = CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude);
            
            [_mapView addAnnotation:pointAnnotation];
        }
    }];
}

// 反地理编码
-(void)reverseGeocoder:(CLLocation*)currentLocation {
    
    NSLog(@"%f %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
       
        if (error || placemarks.count == 0) {
            NSLog(@"error");
        } else {
            CLPlacemark *placemark = placemarks.firstObject;
            
            MKCoordinateRegion region = self.mapView.region;
            region.center = currentLocation.coordinate;
            
            [_mapView setRegion:region animated:YES];
            
            self.titleString = placemark.name;
            
            MKPointAnnotation *pointAnnotation = [[MKPointAnnotation alloc]init];
            pointAnnotation.title = placemark.name;
            pointAnnotation.coordinate = CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude);
            
            [_mapView addAnnotation:pointAnnotation];
        }
    }];
}

#pragma mark - MKMapViewDelegate

-(void)mapViewWillStartLoadingMap:(MKMapView *)mapView {
    
}

-(void)mapViewDidFinishLoadingMap:(MKMapView *)mapView {
    
    
}

// 添加标注时调用
-(void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views {
    NSLog(@"添加标注时调用", nil);
}

// 标注被选中时执行此方法
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    NSLog(@"标注被选中时执行此方法", nil);
    
    if ([view isKindOfClass:[CarDayAnnotationView class]]) {
        CarDayAnnotationView *dayAnnotationView = (CarDayAnnotationView*)view;
        CarDayAnnotation *dayAnnotation = dayAnnotationView.dayAnnotation;
        Car *car = dayAnnotation.car;
        
        [self updateCarInfo:car];
    } else if ([view isKindOfClass:[CarHourAnnotationView class]]) {
        
        CarHourAnnotationView *hourAnnotationView = (CarHourAnnotationView*)view;
        CarHourAnnotation *hourAnnotation = hourAnnotationView.hourAnnotation;
        Car *car = hourAnnotation.car;
        
        [self updateCarInfo:car];
    }
    
    [UIView animateWithDuration:0.5f animations:^{
        self.slider.alpha = .0f;
        self.carView.alpha = 1.0f;
        
        [self.carView setHidden:NO];
        [self.slider setHidden:YES];
    } completion:^(BOOL finished) {
        
    }];
}

// 更新车辆信息
-(void)updateCarInfo:(Car*)car {
    [self.carView setModel:car];
    
    MKCoordinateRegion region = self.mapView.region;
    region.center = CLLocationCoordinate2DMake(car.latitude, car.longitude);
    
    self.mapView.region = [self.mapView regionThatFits:region];
    
    [self.mapView setNeedsDisplay];
}

// 标注失去焦点时执行
-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
    NSLog(@"标注失去焦点时执行", nil);
    
    [self.carView setHidden:YES];
    [self.slider setHidden:NO];
    
    [UIView animateWithDuration:0.5f animations:^{
        self.carView.alpha = 0;
        self.slider.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    NSLog(@"定位成功。");
    
    CLLocation *location = userLocation.location;
    
    self.location = location;
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (error || placemarks.count == 0) {
            NSLog(@"error");
        } else {
            CLPlacemark *placemark = placemarks.firstObject;
            
            MKCoordinateRegion region = self.mapView.region;
            region.center = location.coordinate;
            
            [_mapView setRegion:region animated:YES];
            
            self.titleString = placemark.name;
        }
    }];
}

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[CarDayAnnotation class]]) {
        
         static NSString *key1 = @"key1";
    
        CarDayAnnotationView *annotationView = (CarDayAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:key1];
    
        if (annotationView == nil) {
            annotationView = [[CarDayAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:key1];
            [annotationView setImage:[UIImage imageNamed:@"car3"]];
        }
    
        return annotationView;
    } else if ([annotation isKindOfClass:[CarHourAnnotation class]]) {
        
        static NSString *key2 = @"key2";
        CarHourAnnotationView *annotationView = (CarHourAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:key2];
        
        if (annotationView == nil) {
            annotationView = [[CarHourAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:key2];
            [annotationView setImage:[UIImage imageNamed:@"car4"]];
        }
        
        return annotationView;
    } else {
        // [pinAnnotationView setPinTintColor:[UIColor purpleColor]];
    }
    
    return nil;
}

@end
